package csce315.group10.androidapp;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import org.apache.http.util.ByteArrayBuffer;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxUnlinkedException;

import csce315.group10.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class TopicList extends ListActivity{
	
	/* private instance variables */
		CustomApp appState;
		private final static String TAG = YearBookAppActivity.class.getCanonicalName();
		TopicCatalog topics_from_file = new TopicCatalog();
		
		private void writeFiles(){
	    	final String TAG = YearBookAppActivity.class.getCanonicalName();
			Log.i(TAG, "Write Topics to file.");
	        Serializer serial = new Persister();
	    	File sdcardFile = new File("/sdcard/Topics.xml");

	    	try {
				serial.write(topics_from_file, sdcardFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
	    	// Uploading content.
			FileInputStream fis;
	    	BufferedInputStream bis;
			try {
				fis = new FileInputStream(sdcardFile);
				bis = new BufferedInputStream(fis);
				ByteArrayBuffer baf = new ByteArrayBuffer(50);
		        int current = 0;
		        while ((current = bis.read()) != -1) {
		        	baf.append((byte) current);
		        }
		        ByteArrayInputStream inputStream = new ByteArrayInputStream(baf.toByteArray());
		        Entry newEntry = appState.get_dropbox().putFileOverwrite("/Topics.xml",inputStream,
				           baf.toByteArray().length, null);
		        Log.i("DbLog", "The uploaded file's rev is: " + newEntry.rev);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				 Log.d("Client", "Error: " + e);
			}catch (DropboxUnlinkedException e) {
			   // User has unlinked, ask them to link again here.
			   Log.e("DbLog", "User has unlinked.");
			} catch (DropboxException e) {
			   Log.e("DbLog", "Something went wrong while uploading.");
			}
	    }
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	appState = ((CustomApp)getApplicationContext());
	/* Read and create topic list from xml file */
	  /* Use files to build Topic List */
			Log.i(TAG, "Read Topics from file.");
	        Serializer serial = new Persister();
	    	File sdcardFile = new File("/sdcard/Topics.xml");

	    	try {
	    		topics_from_file = serial.read(TopicCatalog.class, sdcardFile);
			} catch (Exception e) {
				// There is the possibility of error for a number of reasons. Handle this appropriately in your code
				e.printStackTrace();
			}
			Log.i(TAG, "XML Read from File: " + sdcardFile.getAbsolutePath());
	/* get the names of all the contacts */
	String topic_names[] = new String[topics_from_file.getTopics().size()];
	for(int i = 0; i < topics_from_file.getTopics().size(); i++)
	{
		topic_names[i] = topics_from_file.getTopics().get(i).get_topic();
	}
	/* make list fill the whole screen */
	setListAdapter(new ArrayAdapter<String>(this, R.layout.topic_list_item, topic_names));
	
	ListView lv = getListView();
	/* turn on text filtering,so when the user begins typing, the list will be filtered */
	lv.setTextFilterEnabled(true);
	
	/* set action for when a Topic is clicked */
	lv.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view,
	        int position, long id) {
	    	/* When clicked show the contact info */
	    	openTopic((String) ((TextView) view).getText());
	    	}
		});  
    }
    
    /* open screen with the message list */
    private void openTopic(String name){  
    	Intent intent = new Intent();
    	intent.setClass(this,MessageList.class);
    	/* set the chosen topic based on name */
    	for(int i = 0; i < topics_from_file.getTopics().size(); i++)
    	{
    		if(topics_from_file.getTopics().get(i).get_topic().equals(name)){
    			intent.putExtra("topic",topics_from_file.getTopics().get(i).get_topic());
    			Log.d("TopicList","topic name added to intent");
    			break;
    		}
    	}
    	startActivity(intent);
    }
    
    /* create menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	/* only create menu with create and delete options if the user is Editor and Chief */
    	if(appState.get_current_user().get_position().equals("Editor And Chief")){
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.topic_list_menu, menu);
	        return true;
    	}else{
    		MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.limited_topic_list_menu, menu);
	        return true;
    	}
    }
    
    /* set actions for when menu items are selected */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.create_topic:     createTopic();
            							break;
            case R.id.delete_topic:		deleteTopic();
            							break;
        }
        return true;
    }
    
    /* start the dialog to get new contact info */
    private void createTopic(){
    	Intent intent = new Intent();
    	intent.putParcelableArrayListExtra("topics",topics_from_file.getTopics());
    	intent.setClass(this,AddTopicDialog.class);
    	startActivityForResult(intent, 0);
    	
    }
    /* confirm that contact should be deleted */
    private void deleteTopic(){
    	Intent intent = new Intent();
    	intent.setClass(this,DeleteTopicDialog.class);
    	startActivityForResult(intent, 1);
    }
    
    @Override
	public void onActivityResult(int requestCode,int resultCode, Intent data){
    	/* when prompt for new contact returns */
    	/* if back button was pressed then return */
    	if(resultCode != Activity.RESULT_OK){
    		return;
    	}
      if(requestCode == 0){
    	 /* create new topic, but first check to see if already exists */
    	  for(int i = 0; i < topics_from_file.getTopics().size(); i++){
    		  if(topics_from_file.getTopics().get(i).get_topic() == data.getStringExtra("topic")){
    			  Toast.makeText(this, "Topic With That Name Already Exists" , Toast.LENGTH_LONG).show();
    			  return;
    		  }
    	  } 
    	  Topic temp = new Topic(data.getStringExtra("topic"),data.getStringExtra("author"));
    	  /* check for initial message and if it exists then add a message object */
    	  if(data.getStringExtra("initial_message").length() > 0){
    		  temp.getMessages().add(new Message(data.getStringExtra("initial_message"),data.getStringExtra("author")));
    	  }
    	  topics_from_file.getTopics().add(temp);
    	  
    	  
      }else if(requestCode == 1){
    	  /* delete topic */
    	  for(int i = 0; i < topics_from_file.getTopics().size(); i++){
    		  if(topics_from_file.getTopics().get(i).get_topic().equals(data.getStringExtra("topic_name")) ){
    			  topics_from_file.getTopics().remove(i);
    			  break;
    		  }
    	  }  
      }
      /* refresh display updated topics */
      writeFiles();
      startActivity(getIntent()); 
      finish();
    }
    
    public void onDestroy(){
    	super.onDestroy();
		writeFiles();
    }

}